package com.rudolfheszele.smsselector.controller;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rudolfheszele.smsselector.R;
import com.rudolfheszele.smsselector.model.SmsSelectorSmsMessage;
import com.rudolfheszele.smsselector.view.SmsSelectorMessageViewerActivity;
import com.rudolfheszele.smsselector.view.SmsSelectorRuleCreatorActivity;
import com.rudolfheszele.smsselector.view.SmsSelectorRulesViewerActivity;
import com.rudolfheszele.smsselector.view.SmsSelectorSmsViewerActivity;
import com.rudolfheszele.smsselector.view.View;

public class SmsSelectorSmsViewerActivityController implements Controller, OnClickListener
{
	public SmsSelectorSmsViewerActivityController(Activity activity)
	{
		mViewerActivity = (SmsSelectorSmsViewerActivity)activity;
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
		mSelectedFolder = null;
		mMessageViewerIntent = null;
		mRulesViewerIntent = null;
		mRulesCreatorIntent = null;
		mContextView = null;
		mRestoring = false;
	}

	@Override
	public View getView(int viewId)
	{
		return (View)mViewerActivity;
	}
	
	@Override
	public void updateView(View view)
	{
		if(mRestoring == false)
		{
			clearSmsViewerActivity();
			// TODO: Make this method much better...do not use inbox as selected folder every time
			// It is needed when we are coming back from an other activity to this activity...
			registerSmsViewerActivity();
		}
		else
		{
			mRestoring = false;
		}
	}

	@Override
	public void registerView(View view)
	{	
		mViewerActivity = (SmsSelectorSmsViewerActivity)view;
		registerSmsViewerActivity();
	}

	@Override
	public void updateGui(int viewId, Runnable task)
	{	
		mViewerActivity.runOnUiThread(task);
	}
	
	@Override
	public boolean buildMenu(View view, Object menu, Object clicked)
	{
		MenuInflater inflater = mViewerActivity.getMenuInflater();
		Menu optionsMenu = (Menu)menu;
		
		if(clicked == null)
			inflater.inflate(R.menu.smsselector_sms_viewer_activity_options_menu, optionsMenu);
		else
		{
			inflater.inflate(R.menu.smsselector_sms_viewer_activity_context_menu, optionsMenu);
			((ContextMenu)menu).setHeaderTitle(mViewerActivity.getString(R.string.sms_viewer_activity_context_menu_header_text));
			mContextView = (android.view.View)clicked;
		}
		
		return true;
	}
	
	@Override
	public boolean menuClicked(View view, Object menu)
	{
		MenuItem menuItem = (MenuItem)menu;
		SmsSelectorSmsMessage message = null;
		
		switch(menuItem.getItemId())
		{
			case R.id.sms_viewer_activity_manage_rules_options_menu_id:
				mRulesViewerIntent = new Intent(mViewerActivity, SmsSelectorRulesViewerActivity.class);
				mViewerActivity.startActivity(mRulesViewerIntent);
				break;
			case R.id.sms_viewer_activity_create_rule_context_menu_id:
				mRulesCreatorIntent = new Intent(mViewerActivity, SmsSelectorRuleCreatorActivity.class);
				message = mMainController.findSmsMessage(mContextView.getId(), mSelectedFolder.getText().toString());
				// The NEW_RULE is true by default
				mRulesCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.FROM_MESSAGE, true);
				mRulesCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_TEXT, message.getBody());
				mRulesCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_SENDER, message.getAddress());
				mRulesCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_DATE, message.getDate());
				mViewerActivity.startActivity(mRulesCreatorIntent);
				break;
		}
		return true;
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void saveState(int viewId, Object state)
	{
		Bundle bundle = (Bundle)state;
		bundle.putString("SelectedFolder", mSelectedFolder.getText().toString());	
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void restoreState(int viewId, Object state)
	{
		Bundle bundle = (Bundle)state;
		
		mRestoring = true;
		LinearLayout foldersLinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.sms_viewer_activity_folders_linear_layout_id);
		// Deselect the inbox folder, because during registering it is selected by default, but this is not OK for now 
		for(int i = 0; i < foldersLinearLayout.getChildCount(); i++)
		{
			TextView textView = (TextView)foldersLinearLayout.getChildAt(i);
			// Highlight the folder
			if(textView.getText().equals("inbox"))
			{
				textView.setBackgroundColor(Color.BLACK);
				break;
			}
		}
		populateMessagesLinearLayaoutFromFolder(bundle.getString("SelectedFolder"));
	}
	
	@Override
	public void onClick(android.view.View view)
	{
		TextView textView = (TextView)view;
		
		if(textView.getHint().equals(mViewerActivity.getString(R.string.sms_viewer_activity_folders_hint_message_text)))
		{
			// This click event happened on a "Folder"
			if(mSelectedFolder != null)
			{
				if(textView.getText().equals(mSelectedFolder.getText()))
					return;
			}
			else
				mSelectedFolder = textView;
			mSelectedFolder.setBackgroundColor(Color.BLACK);
			mSelectedFolder = textView;
			populateMessagesLinearLayaoutFromFolder(textView.getText().toString());
		}
		else if(textView.getHint().equals(mViewerActivity.getString(R.string.sms_viewer_activity_messages_hint_message_text)))
		{
			// This click event happened on a "Message"
			mMessageViewerIntent = new Intent(mViewerActivity, SmsSelectorMessageViewerActivity.class);
			LinkedList<SmsSelectorSmsMessage> messages = mMainController.getSmsMessages().get(mSelectedFolder.getText().toString());
			Iterator<SmsSelectorSmsMessage> messagesIterator = messages.iterator();
			SmsSelectorSmsMessage selectedMessage = null;
			
			while(messagesIterator.hasNext())
			{
				SmsSelectorSmsMessage message = messagesIterator.next();
				
				if(message.getMessageId() == textView.getId())
				{
					selectedMessage = message;
					break;
				}
			}
			if(selectedMessage == null)
			{
				Toast.makeText(mViewerActivity, "Message could not be found!", 5).show();
				return;
			}
			mMessageViewerIntent.putExtra(SmsSelectorMessageViewerActivityController.FOLDER_KEY, mSelectedFolder.getText().toString());
			mMessageViewerIntent.putExtra(SmsSelectorMessageViewerActivityController.MESSAGE_ID_KEY, textView.getId());
			mViewerActivity.startActivity(mMessageViewerIntent);
		}
	}
	
	private void registerSmsViewerActivity()
	{
		Set<String> folders = mMainController.getSmsMessages().keySet();
		Iterator<String> foldersIterator = folders.iterator();
		LinearLayout foldersLinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.sms_viewer_activity_folders_linear_layout_id);
		
		// Print out the folders on the folders "tab"
		while(foldersIterator.hasNext())
		{
			String folder = foldersIterator.next();
			TextView folderTextView = new TextView(mViewerActivity);
			
			folderTextView.setText(folder);
			
			folderTextView.setOnClickListener(this);
			folderTextView.setHint(R.string.sms_viewer_activity_folders_hint_message_text);
			foldersLinearLayout.addView(folderTextView);
		}
		populateMessagesLinearLayaoutFromFolder("inbox");
	}
	
	private void populateMessagesLinearLayaoutFromFolder(String folder)
	{
		LinkedList<SmsSelectorSmsMessage> folderMessages = mMainController.getSmsMessages().get(folder);
		Iterator<SmsSelectorSmsMessage> folderMessagesIterator = null;
		LinearLayout messagesLinearLayout = null;
		LinearLayout foldersLinearLayout = null;

		if(folderMessages == null)
			return;
		folderMessagesIterator = folderMessages.iterator();
		messagesLinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.sms_viewer_activity_messages_linear_layout_id);
		foldersLinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.sms_viewer_activity_folders_linear_layout_id);
		// Search for the new selected folder
		for(int i = 0; i < foldersLinearLayout.getChildCount(); i++)
		{
			TextView textView = (TextView)foldersLinearLayout.getChildAt(i);
			// Highlight the folder
			if(textView.getText().equals(folder))
			{
				textView.setBackgroundColor(Color.BLUE);
				mSelectedFolder = textView;
				break;
			}
		}
		// Remove messages from the messages "tab"
		messagesLinearLayout.removeAllViews();
		// Print the messages from "folder" to the messages "tab"
		while(folderMessagesIterator.hasNext())
		{
			SmsSelectorSmsMessage message = folderMessagesIterator.next();
			TextView messageTextView = new TextView(mViewerActivity);
			String messageBody = message.getBody();
			int maxMessageLength = 40;
			
			if(messageBody.length() > maxMessageLength)
			{
				messageBody = messageBody.substring(0, maxMessageLength - 3);
				
				messageBody += "...";
			}
			messageTextView.setText(messageBody);
			messageTextView.setOnClickListener(this);
			messageTextView.setHint(R.string.sms_viewer_activity_messages_hint_message_text);
			messageTextView.setId((int)message.getMessageId());
			mViewerActivity.registerForContextMenu(messageTextView);
			messagesLinearLayout.addView(messageTextView);
		}
	}
	
	private void clearSmsViewerActivity()
	{
		mViewerActivity.setContentView(R.layout.smsselector_sms_viewer_activity_layout);
	}

	private SmsSelectorSmsViewerActivity mViewerActivity;
	private SmsSelectorMainController mMainController;
	private TextView mSelectedFolder;
	private Intent mMessageViewerIntent;
	private Intent mRulesViewerIntent;
	private Intent mRulesCreatorIntent;
	private android.view.View mContextView;
	private boolean mRestoring;
}
